{% extends 'admin/base.html' %}

{% block title %}违章记录管理 - 管理后台{% endblock %}
{% block page_title %}违章记录管理{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="bi bi-exclamation-triangle"></i> 违章记录管理</h2>
                <div>
                    <a href="{% url 'bike:export_violations_excel' %}" class="btn btn-outline-success me-2">
                        <i class="bi bi-file-earmark-excel"></i> 导出Excel
                    </a>
                    <a href="{% url 'bike:admin_dashboard' %}" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> 返回仪表盘
                    </a>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-primary text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4 class="card-title" id="total-violations">{{ total_violations }}</h4>
                                    <p class="card-text">总违章数</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-exclamation-triangle display-4"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4 class="card-title" id="pending-count">{{ pending_count }}</h4>
                                    <p class="card-text">待处理</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-clock display-4"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4 class="card-title" id="processing-count">{{ processing_count }}</h4>
                                    <p class="card-text">处理中</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-gear display-4"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-success text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4 class="card-title" id="resolved-count">{{ resolved_count }}</h4>
                                    <p class="card-text">已解决</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-check-circle display-4"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 搜索和筛选 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="get" class="row g-3">
                        <div class="col-md-3">
                            <label for="search" class="form-label">搜索</label>
                            <input type="text" class="form-control" id="search" name="search" 
                                   value="{{ search }}" placeholder="搜索自行车编号、所有人、地点等">
                        </div>
                        <div class="col-md-2">
                            <label for="violation_type" class="form-label">违章类型</label>
                            <select class="form-select" id="violation_type" name="violation_type">
                                <option value="">全部类型</option>
                                {% for type_code, type_name in violation_types %}
                                <option value="{{ type_code }}" {% if violation_type == type_code %}selected{% endif %}>
                                    {{ type_name }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="status" class="form-label">处理状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">全部状态</option>
                                {% for status_code, status_name in status_choices %}
                                <option value="{{ status_code }}" {% if status == status_code %}selected{% endif %}>
                                    {{ status_name }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="college" class="form-label">所属学院</label>
                            <select class="form-select" id="college" name="college">
                                <option value="">全部学院</option>
                                {% for college_code, college_name in colleges %}
                                <option value="{{ college_code }}" {% if college == college_code %}selected{% endif %}>
                                    {{ college_name }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <a href="{% url 'bike:violation_list' %}" class="btn btn-outline-secondary">
                                <i class="bi bi-arrow-clockwise"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 违章记录列表 -->
            <div class="card">
                <div class="card-body">
                    {% csrf_token %}
                    {% if page_obj %}
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>自行车编号</th>
                                    <th>所有人</th>
                                    <th>违章类型</th>
                                    <th>违章地点</th>
                                    <th>检查人</th>
                                    <th>状态</th>
                                    <th>举报时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for violation in page_obj %}
                                <tr>
                                    <td>
                                        <span class="badge bg-primary">{{ violation.bicycle.bike_number }}</span>
                                    </td>
                                    <td>{{ violation.bicycle.owner_name }}</td>
                                    <td>
                                        <span class="badge bg-danger">{{ violation.get_violation_type_display }}</span>
                                    </td>
                                    <td>{{ violation.location }}</td>
                                    <td>{{ violation.reporter_name|default:"匿名" }}</td>
                                    <td>
                                        <select class="form-select form-select-sm status-select" data-violation-id="{{ violation.id }}">
                                            <option value="pending" {% if violation.status == 'pending' %}selected{% endif %}>待处理</option>
                                            <option value="processing" {% if violation.status == 'processing' %}selected{% endif %}>处理中</option>
                                            <option value="resolved" {% if violation.status == 'resolved' %}selected{% endif %}>已解决</option>
                                            <option value="dismissed" {% if violation.status == 'dismissed' %}selected{% endif %}>已撤销</option>
                                        </select>
                                    </td>
                                    <td>
                                        <small class="text-muted">{{ violation.created_at|date:"m-d H:i" }}</small>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-info" 
                                                data-bs-toggle="modal" data-bs-target="#violationModal{{ violation.id }}">
                                            <i class="bi bi-eye"></i> 查看详情
                                        </button>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    {% if page_obj.has_other_pages %}
                    <nav aria-label="分页导航" class="mt-4">
                        <ul class="pagination justify-content-center">
                            <!-- 首页 -->
                            {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page=1{% if search %}&search={{ search }}{% endif %}{% if violation_type %}&violation_type={{ violation_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if college %}&college={{ college }}{% endif %}">
                                    <i class="bi bi-chevron-double-left"></i> 首页
                                </a>
                            </li>
                            {% endif %}

                            <!-- 上一页 -->
                            {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search %}&search={{ search }}{% endif %}{% if violation_type %}&violation_type={{ violation_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if college %}&college={{ college }}{% endif %}">
                                    <i class="bi bi-chevron-left"></i> 上一页
                                </a>
                            </li>
                            {% endif %}

                            <!-- 页码显示 -->
                            {% for num in page_obj.paginator.page_range %}
                                {% if page_obj.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ num }}{% if search %}&search={{ search }}{% endif %}{% if violation_type %}&violation_type={{ violation_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if college %}&college={{ college }}{% endif %}">{{ num }}</a>
                                </li>
                                {% endif %}
                            {% endfor %}

                            <!-- 下一页 -->
                            {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search %}&search={{ search }}{% endif %}{% if violation_type %}&violation_type={{ violation_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if college %}&college={{ college }}{% endif %}">
                                    下一页 <i class="bi bi-chevron-right"></i>
                                </a>
                            </li>
                            {% endif %}

                            <!-- 末页 -->
                            {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if search %}&search={{ search }}{% endif %}{% if violation_type %}&violation_type={{ violation_type }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if college %}&college={{ college }}{% endif %}">
                                    末页 <i class="bi bi-chevron-double-right"></i>
                                </a>
                            </li>
                            {% endif %}
                        </ul>
                        
                        <!-- 分页信息 -->
                        <div class="text-center text-muted small mt-2">
                            显示第 {{ page_obj.start_index }} - {{ page_obj.end_index }} 条，共 {{ page_obj.paginator.count }} 条记录
                            （第 {{ page_obj.number }} 页，共 {{ page_obj.paginator.num_pages }} 页）
                        </div>
                    </nav>
                    {% endif %}

                    {% else %}
                    <div class="text-center py-5">
                        <i class="bi bi-check-circle display-1 text-success"></i>
                        <h4 class="text-muted mt-3">暂无违章记录</h4>
                        <p class="text-muted">所有自行车都表现良好！</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 违章详情模态框 -->
{% for violation in page_obj %}
<div class="modal fade" id="violationModal{{ violation.id }}" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">违章详情 - {{ violation.bicycle.bike_number }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>自行车编号：</strong>{{ violation.bicycle.bike_number }}</p>
                        <p><strong>所有人：</strong>{{ violation.bicycle.owner_name }}</p>
                        <p><strong>违章类型：</strong>{{ violation.get_violation_type_display }}</p>
                        <p><strong>违章地点：</strong>{{ violation.location }}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>检查人：</strong>{{ violation.reporter_name|default:"匿名" }}</p>
                        <p><strong>举报电话：</strong>{{ violation.reporter_phone|default:"未提供" }}</p>
                        <p><strong>举报时间：</strong>{{ violation.created_at|date:"Y年m月d日 H:i" }}</p>
                        <p><strong>当前状态：</strong>
                            <span id="modal-status-{{ violation.id }}">
                                {% if violation.status == 'pending' %}
                                <span class="badge bg-warning">待处理</span>
                                {% elif violation.status == 'processing' %}
                                <span class="badge bg-info">处理中</span>
                                {% elif violation.status == 'resolved' %}
                                <span class="badge bg-success">已解决</span>
                                {% else %}
                                <span class="badge bg-secondary">已撤销</span>
                                {% endif %}
                            </span>
                        </p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12">
                        <p><strong>违章描述：</strong></p>
                        <p>{{ violation.description }}</p>
                    </div>
                </div>
                {% if violation.violation_images %}
                <div class="row">
                    <div class="col-12">
                        <p><strong>违章照片：</strong></p>
                        <img src="{{ violation.violation_images.url }}" alt="违章照片" class="img-fluid">
                    </div>
                </div>
                {% endif %}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endfor %}
{% endblock %}

{% block extra_js %}
<script>
// 更新模态框中的状态显示
function updateModalStatus(violationId, newStatus) {
    const modalStatusElement = document.getElementById(`modal-status-${violationId}`);
    if (modalStatusElement) {
        console.log(`更新模态框状态: ${violationId} -> ${newStatus}`);
        
        // 状态映射
        const statusMap = {
            'pending': { text: '待处理', class: 'badge bg-warning' },
            'processing': { text: '处理中', class: 'badge bg-info' },
            'resolved': { text: '已解决', class: 'badge bg-success' },
            'dismissed': { text: '已撤销', class: 'badge bg-secondary' }
        };
        
        const statusInfo = statusMap[newStatus];
        if (statusInfo) {
            modalStatusElement.innerHTML = `<span class="${statusInfo.class}">${statusInfo.text}</span>`;
            console.log(`模态框状态已更新: ${statusInfo.text}`);
        }
    } else {
        console.log(`未找到模态框状态元素: modal-status-${violationId}`);
    }
}

// 更新统计卡片数据
function updateStatistics(oldStatus, newStatus) {
    console.log(`更新统计数据: ${oldStatus} -> ${newStatus}`);
    
    // 获取当前统计数字
    const totalElement = document.getElementById('total-violations');
    const pendingElement = document.getElementById('pending-count');
    const processingElement = document.getElementById('processing-count');
    const resolvedElement = document.getElementById('resolved-count');
    
    if (!totalElement || !pendingElement || !processingElement || !resolvedElement) {
        console.log('未找到统计元素');
        return;
    }
    
    // 获取当前数值
    let totalCount = parseInt(totalElement.textContent) || 0;
    let pendingCount = parseInt(pendingElement.textContent) || 0;
    let processingCount = parseInt(processingElement.textContent) || 0;
    let resolvedCount = parseInt(resolvedElement.textContent) || 0;
    
    console.log(`当前统计: 总数=${totalCount}, 待处理=${pendingCount}, 处理中=${processingCount}, 已解决=${resolvedCount}`);
    
    // 根据状态变化更新计数
    if (oldStatus !== newStatus) {
        // 减少旧状态计数
        if (oldStatus === 'pending') {
            pendingCount = Math.max(0, pendingCount - 1);
        } else if (oldStatus === 'processing') {
            processingCount = Math.max(0, processingCount - 1);
        } else if (oldStatus === 'resolved') {
            resolvedCount = Math.max(0, resolvedCount - 1);
        }
        
        // 增加新状态计数
        if (newStatus === 'pending') {
            pendingCount += 1;
        } else if (newStatus === 'processing') {
            processingCount += 1;
        } else if (newStatus === 'resolved') {
            resolvedCount += 1;
        }
        
        // 更新显示
        pendingElement.textContent = pendingCount;
        processingElement.textContent = processingCount;
        resolvedElement.textContent = resolvedCount;
        
        console.log(`更新后统计: 总数=${totalCount}, 待处理=${pendingCount}, 处理中=${processingCount}, 已解决=${resolvedCount}`);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    console.log('违章记录管理页面加载完成');
    
    // 初始化状态选择器的旧状态
    document.querySelectorAll('.status-select').forEach(function(select) {
        select.dataset.oldStatus = select.value;
        console.log(`初始化状态: ${select.dataset.violationId} -> ${select.value}`);
    });
    
    // 处理状态更新
    document.querySelectorAll('.status-select').forEach(function(select) {
        console.log('绑定状态选择器事件:', select.dataset.violationId);
        
        select.addEventListener('change', function() {
            const violationId = this.dataset.violationId;
            const newStatus = this.value;
            const oldStatus = this.dataset.oldStatus || 'pending'; // 获取旧状态
            
            console.log('状态更新请求:', {
                violationId: violationId,
                oldStatus: oldStatus,
                newStatus: newStatus
            });
            
            // 使用Django URL反向解析
            const updateUrl = '{% url "bike:violation_update_status" 0 %}'.replace('0', violationId);
            console.log('更新URL:', updateUrl);
            
            fetch(updateUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: `status=${newStatus}`
            })
            .then(response => {
                console.log('响应状态:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('响应数据:', data);
                if (data.success) {
                    // 更新模态框中的状态显示
                    updateModalStatus(violationId, newStatus);
                    
                    // 更新统计数据
                    updateStatistics(oldStatus, newStatus);
                    
                    // 更新旧状态记录
                    this.dataset.oldStatus = newStatus;
                    
                    // 显示成功消息
                    const alert = document.createElement('div');
                    alert.className = 'alert alert-success alert-dismissible fade show';
                    alert.innerHTML = `
                        ${data.message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.querySelector('.container-fluid').insertBefore(alert, document.querySelector('.row'));
                    
                    // 3秒后自动隐藏消息
                    setTimeout(() => {
                        alert.remove();
                    }, 3000);
                } else {
                    // 恢复原状态
                    this.value = oldStatus;
                    alert('更新失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('更新状态错误:', error);
                // 恢复原状态
                this.value = oldStatus;
                alert('更新失败，请重试');
            });
        });
    });
    
    // 监听模态框显示事件，确保状态是最新的
    document.querySelectorAll('[data-bs-target^="#violationModal"]').forEach(function(button) {
        button.addEventListener('click', function() {
            const modalId = this.getAttribute('data-bs-target');
            const violationId = modalId.replace('#violationModal', '');
            
            // 获取当前表格中的状态
            const statusSelect = document.querySelector(`[data-violation-id="${violationId}"]`);
            if (statusSelect) {
                const currentStatus = statusSelect.value;
                console.log(`模态框打开，同步状态: ${violationId} -> ${currentStatus}`);
                updateModalStatus(violationId, currentStatus);
            }
        });
    });
});
</script>
{% endblock %}